package telebase;

import java.awt.Component;
import java.awt.Container;
import java.awt.FocusTraversalPolicy;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class CompanyJobsFrame extends javax.swing.JDialog {

    private DB db = new DB();
    private Integer SelectedObjectID = -1;

    private static class MyFocusTraversalPolicy extends FocusTraversalPolicy {

        Vector<Component> order;
        Integer cur = 0;

        public MyFocusTraversalPolicy(Vector<Component> order) {
            this.order = new Vector<Component>(order.size());
            this.order.addAll(order);
        }

        @Override
        public Component getComponentAfter(Container aContainer, Component aComponent) {
            cur++;
            if (cur.equals(order.size())) {
                cur = 0;
            }
            return order.get(cur);
        }

        @Override
        public Component getComponentBefore(Container aContainer, Component aComponent) {
            cur--;
            if (cur < 0) {
                cur = order.size() - 1;
            }
            return order.get(cur);
        }

        @Override
        public Component getFirstComponent(Container aContainer) {
            return order.get(0);
        }

        @Override
        public Component getLastComponent(Container aContainer) {
            return order.lastElement();
        }

        @Override
        public Component getDefaultComponent(Container aContainer) {
            return order.get(0);
        }
    }
    ArrayList<WorkObj> wol = new ArrayList<WorkObj>();

    public CompanyJobsFrame(java.awt.Frame parent, boolean modal, Boolean forSelect) {
        super(parent, modal);
        initComponents();
        if (!forSelect) {
            jButton5.setVisible(false);
        }
        i18n();
        jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        Vector<Component> order = new Vector<Component>();
        order.add(jTree1);
        order.add(jButton5);
        order.add(jButton4);
        order.add(jButton3);
        order.add(jButton1);
        order.add(jButton2);
        MyFocusTraversalPolicy traversalpolicy = new MyFocusTraversalPolicy(order);
        setFocusTraversalPolicy(traversalpolicy);

        RefreshTreeModel();
    }

    private void i18n() {
        setTitle(i18n.get("kjf_title"));
        jButton1.setText(i18n.get("kjf_edit"));
        jButton2.setText(i18n.get("kjf_delete"));
        jButton3.setText(i18n.get("kjf_add"));
        jButton4.setText(i18n.get("kjf_close"));
        pack();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jButton3 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Company, departament, job title...");
        setMinimumSize(new java.awt.Dimension(450, 500));
        setModal(true);

        jTree1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTree1MouseClicked(evt);
            }
        });
        jTree1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTree1KeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTree1);

        jButton3.setText("Add");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton1.setText("Edit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Delete");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton4.setText("Close");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Select");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 759, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 411, Short.MAX_VALUE)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 502, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
        if (node == null) {
            node = (DefaultMutableTreeNode) jTree1.getModel().getRoot();
        }

        CompanyJobsAdd dlg = new CompanyJobsAdd(null, true);
        dlg.setLocationRelativeTo(this);
        dlg.setVisible(true);

        if (dlg.hasChanges()) {

            Integer New_k;
            Integer New_workpar;

            if (node.isRoot()) {
                New_workpar = 0;
            } else {
                WorkObj wo = (WorkObj) node.getUserObject();
                New_workpar = wo.getK();
            }

            String New_workname = dlg.getText();
            New_workname = db.getPrepS(New_workname);

            New_k = db.executeNonQueryAI("INSERT INTO worknames (workpar, workname) VALUES (" + New_workpar + ", \"" + New_workname + "\")");

            DefaultMutableTreeNode child = new DefaultMutableTreeNode(
                    new WorkObj(
                    New_k,
                    New_workpar,
                    dlg.getText()));
            node.add(child);
            jTree1.setSelectionPath(new TreePath(child.getPath()));
            jTree1.setSelectionPath(new TreePath(node.getPath()));
            jTree1.updateUI();
        }
}//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
        if (node == null || node.isRoot()) {
            return;
        }

        CompanyJobsEdit dlg = new CompanyJobsEdit(null, true);
        dlg.setLocationRelativeTo(this);
        dlg.setWorkObject((WorkObj) node.getUserObject());
        dlg.setVisible(true);

        if (dlg.hasChanges()) {
            WorkObj wo = dlg.getWorkObject();
            db.executeNonQuery("UPDATE worknames " +
                    "SET workname=\"" + db.getPrepS(wo.getWorkname()) + "\" " +
                    "WHERE k=" + wo.getK());
            node.setUserObject(wo);
            jTree1.updateUI();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
        if (node == null || node.isRoot()) {
            return;
        }

        if (JOptionPane.showConfirmDialog(null,
                i18n.get("kjf_del_conf_q"),
                i18n.get("kjf_del_conf_c"),
                JOptionPane.YES_NO_OPTION) ==
                JOptionPane.YES_OPTION) {

            Enumeration e = node.preorderEnumeration();
            while (e.hasMoreElements()) {
                DefaultMutableTreeNode n = (DefaultMutableTreeNode) e.nextElement();
                WorkObj wo = (WorkObj) n.getUserObject();
                db.executeNonQuery("DELETE FROM worknames WHERE k=" + wo.getK());
                db.executeNonQuery("DELETE FROM works WHERE workid=" + wo.getK());
            }

            RefreshTreeModel();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
        if (node == null || node.isRoot()) {
            return;
        }
        WorkObj wo = (WorkObj) node.getUserObject();
        SelectedObjectID = wo.getK();
        dispose();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jTree1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTree1KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            if (jButton5.isVisible()) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                if (node == null || node.isRoot()) {
                    return;
                }
                WorkObj wo = (WorkObj) node.getUserObject();
                SelectedObjectID = wo.getK();
                dispose();
            }
        }
    }//GEN-LAST:event_jTree1KeyReleased

    private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTree1MouseClicked
        if (jButton5.isVisible()) {
            if (evt.getClickCount() > 1) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
                if (node.isLeaf()) {
                    WorkObj wo = (WorkObj) node.getUserObject();
                    SelectedObjectID = wo.getK();
                    dispose();
                }
            }
        }
    }//GEN-LAST:event_jTree1MouseClicked

    public Integer getSelectedObjectID() {
        return SelectedObjectID;
    }

    public String getSelectedObjectString() {
        String s = "";
        WorkObj wo = null;
        Boolean nextparent = true;

        Integer k = getSelectedObjectID();
        if (k.equals(-1)) {
            return s;
        }

        while (nextparent) {
            ResultSet rs = db.getResultSet("SELECT k, workpar, workname FROM worknames WHERE k=" + k);
            try {
                rs.next();
                wo = new WorkObj(rs.getInt("k"), rs.getInt("workpar"), rs.getString("workname"));
            } catch (SQLException ex) {
                System.out.println(ex.getMessage());
            }
            db.closeResultSet();

            if (s.equals("")) {
                s = wo.getWorkname();
            } else {
                s = wo.getWorkname() + ", " + s;
            }

            k = wo.getWorkpar();

            if (k.equals(0)) {
                nextparent = false;
            }
        }

        return s;
    }

    private void RefreshTreeModel() {
        WaitingWindow waw = new WaitingWindow();

        DefaultMutableTreeNode top = new DefaultMutableTreeNode(i18n.get("kjf_all"));
        WorkObj wo = null;
        wol.clear();

        ResultSet rs = db.getResultSet("SELECT k, workpar, workname FROM worknames ORDER BY k");
        try {
            while (rs.next()) {
                wo = new WorkObj(rs.getInt("k"), rs.getInt("workpar"), rs.getString("workname"));
                wol.add(wo);
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        db.closeResultSet();

        RefreshTreeModelReq(0, top);

        DefaultTreeModel tm = new DefaultTreeModel(top);
        jTree1.setModel(tm);

        waw.close();
    }

    private void RefreshTreeModelReq(Integer k, DefaultMutableTreeNode node) {
        for (WorkObj w : wol) {
            if (w.getWorkpar().equals(k)) {
                DefaultMutableTreeNode dmtn = new DefaultMutableTreeNode(w);
                node.add(dmtn);
                RefreshTreeModelReq(w.getK(), dmtn);
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables
    }
